import PropTypes from 'prop-types'
import React, { Component } from 'react'
import PubSub from "pubsub-js";

import './index.css'

export default class Search extends Component {
  state = {
    words:"",
  }
  //static propTypes = {second: third}

  changeWords=(e)=>{
    this.setState({
      words: e.target.value
    })
  }

  search = async ()=>{
    const {words:key} = this.state
    const url = `https://api.github.com/search/users?q=${key}`;

    // 发送请求之前更新state
    // this.props.updateAppState({isFirst:false, isLoading:true})
    PubSub.publish('changeState', {isFirst:false, isLoading:true})

    /*
    fetch(url, {
      headers: {'Content-Type':'application/json'}
    }).then(response=>response.json())
    .then(result=>{
      PubSub.publish('changeState', {isLoading:false, users:result.items})
    })
    .catch(error=>{
      PubSub.publish('changeState', {isLoading:false, err:error.message})
    })
    */

    try {
      const resp = await fetch(url);
      const json = await resp.json();
      PubSub.publish('changeState', {isLoading:false, users:json.items})
    }catch(e){
      PubSub.publish('changeState', {isLoading:false, err:e.message})
    }
  }

  render() {
    return (
      <header className="header">
      <h2>搜索Github用户</h2>
      <div className="search">
        <input type="text" placeholder="输入关键词点击搜索" onChange={this.changeWords}/>
        &nbsp;<button onClick={this.search}>搜索</button>
      </div>
    </header>
    )
  }
}
